package com.ellecity06.cwhiskymall.ui.share.poster

import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.bean.GoodImageBean
import com.ellecity06.cwhiskymall.bean.request.GoodRequest
import com.ellecity06.cwhiskymall.bean.request.H5UrlRequest
import com.ellecity06.cwhiskymall.bean.response.GoodDetailResponse
import com.ellecity06.cwhiskymall.bean.response.GoodResponse
import com.ellecity06.cwhiskymall.http.request
import com.ellecity06.cwhiskymall.ui.invite.InviteFriendState

/**
 * @author ellecity06
 * @time 2024/11/4 13:34
 * @des
 */
class SharePosterViewModel : BaseMviViewModel<SharePosterState, SharePosterIntent>() {
    private var good: GoodDetailResponse? = null
    override suspend fun collectIntent(it: SharePosterIntent) {
        when (it) {
            is SharePosterIntent.FetchGoodDetail -> {
                fetchGoodDetail(it.id)
            }
            SharePosterIntent.GetH5Url -> {
//                getRegisterH5()
            }
        }
    }

    private fun getRegisterH5() {
        request(api = { getH5RequestUrl(H5UrlRequest("h5_register_url")) }, success = {
            if (it != null) {
                mState.postEvent(SharePosterState.H5Url(it.url ?: "", this.good))
            }

        })
    }

    private fun fetchGoodDetail(id: Int) {
        request(api = { getGoodsDetail(GoodRequest(id = id)) }, success = {
            getRegisterH5()
            if (it != null) {
                good = it
                mState.postEvent(SharePosterState.GoodDetail(it))
            }
            if (it?.spuImages != null) {
                val images = it.spuImages.map { url -> GoodImageBean(image = url) }.toMutableList()
                if (images.isNotEmpty()) images[0].checked = true
                mState.postEvent(SharePosterState.GoodImageSuccess(images))
            }
            if (it?.spuName != null) {
                mState.postEvent(SharePosterState.GoodDesc(it.spuName))
            }
        })
    }
}